﻿#region MIT License
/*

Copyright (C) 2011 by Timothy A. Barela

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/
#endregion

using System;
using System.Diagnostics;
using System.Reflection;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Metadata;

using CecilTypeAttributes = Mono.Cecil.TypeAttributes;

namespace Sharpener
{
	/// <summary>
	/// Adds the Sharpened attribute to the assembly, showing that its been optimized using Sharpener.
	/// </summary>
	public class WatermarkPass : Pass
	{
		public override string StartingMessage
		{
			get { return "Marking assembly as Sharpened."; }
		}

		public override bool Run( AssemblyDefinition assembly )
		{
			var watermarkDef = buildSharpenedAttribute( assembly );
						
			assembly.MainModule.Types.Add(watermarkDef);
			
			//apply attribute to assembly

			//we know 0 is hardcoded to our ctor here...
			var ca = new CustomAttribute(watermarkDef.Methods[0]); 
			assembly.CustomAttributes.Add(ca);
					
			return true;
		}

		private TypeDefinition buildSharpenedAttribute( AssemblyDefinition assembly )
		{
			var module = assembly.MainModule;

			var def = new TypeDefinition("Sharpener", "SharpenedAttribute",
								CecilTypeAttributes.NotPublic |
								CecilTypeAttributes.Class |
								CecilTypeAttributes.Sealed,
								module.Import(typeof(Attribute)));

			var ctorflags = //Mono.Cecil.MethodAttributes.Public |
					Mono.Cecil.MethodAttributes.RTSpecialName |
					Mono.Cecil.MethodAttributes.SpecialName |
					Mono.Cecil.MethodAttributes.HideBySig;


			//add versioning info
			//def.Properties.Add(createVersionProperty()); 

			//add a constructor
			var meth = new MethodDefinition(".ctor", ctorflags, module.Import(typeof(void)));

			def.Methods.Add(meth);

			meth.Body.MaxStackSize = 8;
			var il = meth.Body.GetILProcessor();

			//var info = typeof(Attribute).GetConstructor(Type.EmptyTypes);//wont find protected base ctor :(
			var info = typeof(Attribute).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance)[0];   

			var baseCtorRef = module.Import(info);

			il.Append(Instruction.Create(OpCodes.Ldarg_0));
			il.Append(Instruction.Create(OpCodes.Call, baseCtorRef ));
			il.Append(Instruction.Create(OpCodes.Ret)); 


			//apply AttributeUsage...
			var ctor = module.Import(typeof(AttributeUsageAttribute).GetConstructor(new Type[] { typeof(AttributeTargets) }));
			var ca = new CustomAttribute(ctor);

			var arg = new CustomAttributeArgument(module.Import(typeof(AttributeUsageAttribute)), AttributeTargets.Assembly);
			ca.ConstructorArguments.Add(arg);

			def.CustomAttributes.Add(ca);
								
			return def;
		}

		//private PropertyDefinition createVersionProperty(ModuleDefinition module)
		//{
		//    //var version = Assembly.GetExecutingAssembly().GetName().Version;
		//    var propDef = new PropertyDefinition("Version",Mono.Cecil.PropertyAttributes.None,module.Import(typeof(string)));
			

		//    return propDef;
		//}
	}
}